package com.bw.cinema.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.cinema.intent.MutilVideoIntent
import com.bw.cinema.service.MutilVideoService
import com.bw.cinema.state.MutilVideoState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class MutilVideoViewModel : BaseViewModel<MutilVideoIntent>() {
    private val service: MutilVideoService by lazy { MutilVideoService() }
    private val _state = MutableStateFlow<MutilVideoState>(MutilVideoState.init)

    val state: StateFlow<MutilVideoState>
        get() = _state

    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is MutilVideoIntent.getMutilVideoIntent -> {
                        doMutilVideo(it)
                    }


                    else -> {}
                }
            }
        }
    }

    private fun doMutilVideo(it: MutilVideoIntent.getMutilVideoIntent) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getMutilVideo(it.page, it.size, it.id)
            if (data.code == 0) {
                _state.value = MutilVideoState.getMutilVideoState(data.data)
            } else {
                _state.value = MutilVideoState.Failed
            }
        }
    }
}